package com.fire.core.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.MessageFormat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import com.fire.core.jkmodel.XmlMessageDTO;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


/**
 *类描述：
 *@author: Aspire
 *@date： 日期：2018年4月20日 时间：下午3:26:19
 *@version 1.0
 */
public class XmlMessageUtil {
	private static final String XML_MESSAGE_TPL = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Package><PartnerCode>{0}</PartnerCode><Sign>{1}</Sign><Content><![CDATA[{2}]]></Content></Package>";
	
	public static String createXml(String partnerCode, String sign, String content){
		return MessageFormat.format(XML_MESSAGE_TPL, partnerCode, sign, content);
	}
	
	public static XmlMessageDTO parseXml(String xmlMessageStr) {
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder;
		XmlMessageDTO xmlMessageDTO = new XmlMessageDTO();
		try(ByteArrayInputStream bis = new ByteArrayInputStream(xmlMessageStr.getBytes("utf-8"))) {
			documentBuilder = documentBuilderFactory.newDocumentBuilder();
			Document document = documentBuilder.parse(bis);
			xmlMessageDTO.setContent(document.getElementsByTagName("Content").item(0).getTextContent());
			xmlMessageDTO.setSign(document.getElementsByTagName("Sign").item(0).getTextContent());
			xmlMessageDTO.setPartnerCode(document.getElementsByTagName("PartnerCode").item(0).getTextContent());
		} catch (Exception e) {
			throw new RuntimeException("解析失败");
		}
		return xmlMessageDTO;
	}
	
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		parseXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Package><PartnerCode>PartnerCode</PartnerCode><Sign>Sign</Sign><Content><![CDATA[你好啊]]></Content></Package>");
	}
	
}
